package com.example.demo.utils;

import com.example.demo.Enums.SexEnum;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import org.springframework.boot.jackson.JsonComponent;

import java.io.IOException;

/**
 * The type Wen serialization.
 * 自定义序列化
 * JsonComponent  该注解用于直接注释实现或包含它们作为内部类的类
 */
@JsonComponent
public class WenSerialization {

    /**
     * 序列化，即将Java对象转为JSON，用于将Java对象转为前端所需的结果
     */
    public static class ResultSerializer extends JsonSerializer<SexEnum> {

        @Override
        public void serialize(SexEnum sexEnum, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
            jsonGenerator.writeString(sexEnum.getSexStr());
        }
    }

    /**
     * 反序列化，将JSON转为Java对象，用于接收前端参数
     */
    public static class ResultDeSerializer extends JsonDeserializer<SexEnum> {

        @Override
        public SexEnum deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
            ObjectCodec codec = jsonParser.getCodec();
            JsonNode treeNode = codec.readTree(jsonParser);
            int code = treeNode.intValue();
            return SexEnum.valueOf(code);
        }
    }
}
